<template>
	<ex-dialog v-model="visible" draggable title="导入资产" :width="600" :contentHeight="215" :top="160">
		<template #default>
			<el-progress v-if="loading" :text-inside="true" :stroke-width="20" :percentage="percentage"/>
			<div v-loading="loading">
				<el-upload
					drag
					class="upload-demo" ref="upload" accept=".xls,.xlsx"
					action=""
					:on-change="upload"
					:show-file-list="false"
					:auto-upload="false"
					>
					<slot name="uploader">
						<el-icon class="el-icon--upload"><el-icon-upload-filled /></el-icon>
						<div class="el-upload__text">
							将文件拖到此处或 <em>点击选择文件上传</em>
						</div>
					</slot>
					<template #tip>
						<div class="el-upload__tip">
							<template v-if="tip">{{tip}}</template>
							<template v-else>请上传小于或等于 {{maxSize}}M 的 {{accept}} 格式文件</template>
							<el-link @click="downloadTemplate" target="_blank" type="primary" :underline="false">下载导入模板</el-link>
						</div>
					</template>
				</el-upload>
				<el-form v-if="$slots.form" inline label-width="100px" label-position="left" style="margin-top: 18px;">
					<slot name="form" :formData="formData"></slot>
				</el-form>
			</div>
		</template>
		  <template #footer>
			<div style="flex: auto;text-align: center;">
				<el-button plain type="primary" @click="save" :loading="loading">确 认</el-button>
				<el-button plain type="info" @click="this.visible = false" :loading="loading">关 闭</el-button>
          </div>
		</template>
	</ex-dialog>
</template>

<script>
import * as xlsx from "xlsx";
import globalparam from "@/constant/model/globalparam";
import exDialog from '@/components/exDialog'
import validare from "@/utils/verificate";

export default {
	name:"importAsset",
	computed: {},
	emits: ['success'],
	components: {
		exDialog
	},
	props: {
		menu: {
			type: Object, default: () => {
			}
		},
		accept: { type: String, default: ".xls, .xlsx" },
			maxSize: { type: Number, default: 10 },
			tip: { type: String, default: "" },
	},
	data() {
		return {
			visible: false,
			form: {},
			loading: false,
			importAssets:[],
		}
	},
	watch: {},
	mounted() {

	},
	onLoad() {
	},
	methods: {
		//显示
		open(entity) {
			this.importAssets=[];
			this.form = Object.assign({}, entity);
			this.oldForm = Object.assign({}, this.form);
			this.visible = true;
		},
		async close(){
      this.visible = false;
    },
		//保存
		async save() {
			if (this.importAssets.length===0) {
				this.$message.error('未读取到资产信息，请确认上传的文件是否符合要求')
				return ;
			}

			try {
				this.loading = true
				let data = {
					importAssets:this.importAssets,
					documentId:this.form.documentId,
					manageDeptIds:this.$TOOL.current.manageDeptIds(),//当前身份的管理部门
					assetCategoryIds:this.form.assetCategoryIds,//当前单据的可操作资产分类
					assetStatusIds:this.form.assetStatusIds,//当前单据可操作的资产状态
					financialTypes:this.form.financialTypes,//当前单据可操作的财务类型
					isIncludeCheckAsset:this.form.isIncludeCheckAsset,//是否可操作盘点中的资产
					documentType:this.form.documentType,
					usingDepartmentIds: this.$TOOL.current.manageDeptIds(),//变动后的使用部门范围
				};

				if(this.form.documentType==='allocate'){
					let innerRangeDeptIds = this.$TOOL.current.innerRangeDeptIds();//所在部门范围内的部门id
					let allDeptOptions = await this.$cache.dic.options("SysOrganization", true);
					let allDeptIds = [];
					//查询所有部门，并取所在部门范围之外的其它部门id
					if(allDeptOptions&&Array.isArray(allDeptOptions)){
						allDeptOptions.forEach(item=>{
							if(!innerRangeDeptIds.includes(item.value)){
								allDeptIds.push(item.value);
							}
						});
					}
					//如果没有其它部门，则设置为一默认的none值，使用查询的数据为空
					if(allDeptIds.length===0){
						allDeptIds.push("none")
					}

					//闲置调入时的可操作部门范围，在组织范围之外,调入后的使用部门在组织范围之内
					if(this.form.processTypeCode==='XZDR'){
						data.manageDeptIds = allDeptIds;
						data.usingDepartmentIds = innerRangeDeptIds;
					}
					//资产调出时的可操作部门范围，在组织范围之内，调入后的使用部门在组织机构的范围之内
					if(this.form.processTypeCode==='ZCDC'){
						data.manageDeptIds = this.$TOOL.current.manageDeptIds();
						data.usingDepartmentIds = allDeptIds;
					}

				}

				let res = await this.$API.asset.documentDetail.import.post(data);
				if(res.code===2000){
          if(res.data.invalidData.length>0){
            this.$message.warning("上传数据："+res.data.importDataSize+" 条, 有效数据："+res.data.validDataSize+" 条, 无效数据"+res.data.invalidData.length+" 条,已为您自动下载导入结果.")
            this.downloadImportResult(res.data.invalidData);
          }else{
            this.$message.success("上传数据："+res.data.importDataSize+" 条, 有效数据："+res.data.validDataSize+" 条, 无效数据"+res.data.invalidData.length+" 条.")
          }
          this.$emit('success');
				}
				this.visible = false;
			}finally {
				this.loading = false;
			}
		},

    downloadImportResult(data) {
      if(Array.isArray(data)){
        let firstData = data[0];
        let tableHeader = [];
        for (let header in firstData ){
            tableHeader.push(header);
        }
        let tableData = [];
        data.forEach(row=>{
            let rowData = [];
          tableHeader.forEach(header=>{
			  let value = row[header]+"";
			  if(value.startsWith("0")&&validare.isNumber(value)){
				  rowData.push("`"+value);
			  }else{
				  rowData.push(value);
			  }
          });
          tableData.push(rowData);
        });
        // 生成XLS文件内容
        let content = '';
        content += tableHeader.join('\t') + '\n'; // 添加表头
        for (let row of tableData) {
          content += row.join('\t') + '\n'; // 添加数据行
        }
        // 创建Blob对象
        const blob = new Blob([content], { type: 'application/vnd.ms-excel' });
        // 创建下载链接
        const downloadLink = document.createElement('a');
        downloadLink.href = URL.createObjectURL(blob);
        downloadLink.download = 'invalidData'+this.$TOOL.uuid("")+'.xlsx';
        // 模拟点击下载链接
        downloadLink.click();
        this.$confirm(`请至浏览器的下载记录中查看导入失败的详情`, '提示', {
          type: 'warning',
        }).then(() => {
          return true
        }).catch(() => {
          return false
        })
      }
    },

		async downloadTemplate() {
			let minioServerUrl = await this.$TOOL.minioServerUrl();
			let paramValue = await this.$cache.data.loadGlobalParam(globalparam.documentDetailImportTemplate.paramCode);
			let templateUrl = null;
			if (paramValue&&paramValue[this.form.documentConfigId]) {
				let tempFiles = this.$TOOL.toObj(paramValue[this.form.documentConfigId]);
				if (tempFiles[0]) {
					templateUrl = minioServerUrl + tempFiles[0].realUrl;
				}
			}
			if (!templateUrl) {
				this.$message.error("未找到导入模板");
				return;
			}
			window.open(templateUrl);
		},
		upload (file, fileList) {
			const files = { 0: file.raw }// 取到File
			this.readExcel(files)
		},
		readExcel (files) { // 表格导入
			if (files.length <= 0) { // 如果没有文件名
				return false
			} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
				this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
				return false
			}

			const fileReader = new FileReader()
			fileReader.onload = (files) => {
				this.importAssets=[];
				try {
					const data = files.target.result
					const workbook = xlsx.read(data, {
						type: 'binary'
					})
					const wsname = workbook.SheetNames[0]// 取第一张表
					const ws = xlsx.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
					// 重写数据
					this.$refs.upload.value = ''
					if(ws.length>0){
						ws.forEach(row=>{
							this.importAssets.push(row);
						})
					}
					this.$message.success("导入的文件中包含了"+this.importAssets.length+"条数据");
				} catch (e) {
					//console.log(e)
					return false
				}
			}
			fileReader.readAsBinaryString(files[0])
		},

	}
}
</script>

<style scoped>
h2 {
	font-size: 17px;
	color: #3c4a54;
	padding: 0 0 30px 0;
}

[data-theme="dark"] h2 {
	color: #fff;
}


::v-deep(.dialogselect .el-dialog__header){
  padding: 0px !important;
  margin-right: 0px;
}
::v-deep(.dialogsearch){
 padding-top: 10px;
}

::v-deep(.dialogsearch .el-form-item--default .el-form-item__label){
  font-size: 13px !important;
}

::v-deep(.dialogsearch .el-form-item--default .el-input__inner,.dialogsearch .el-form-item--default .el-date-editor){
  font-size: 13px !important;

}
::v-deep(.upload-demo){
width:96%;
margin-left: 2%;
margin-top: 10px;
}

</style>
